package com.bawei.module_message.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_message.databinding.LayoutItemMessageBinding
import com.bawei.module_message.model.MessageModelItem

class MessageAdapter : RecyclerView.Adapter<MessageAdapter.ViewHolder>(){

    private val diffCallback = object : DiffUtil.ItemCallback<MessageModelItem>() {
        override fun areItemsTheSame(oldItem: MessageModelItem, newItem: MessageModelItem): Boolean {
            return oldItem.id == newItem.id // 根据唯一标识判断 item 是否相同
        }

        override fun areContentsTheSame(oldItem: MessageModelItem, newItem: MessageModelItem): Boolean {
            return oldItem == newItem // 判断 item 内容是否相同，数据类重写了 equals 可直接用
        }
    }

    fun submitList(newData : List<MessageModelItem>?) = differ.submitList(newData)

    private val differ = AsyncListDiffer(this,diffCallback)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = LayoutItemMessageBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val message = differ.currentList[position]
        holder.binding.view = message
        holder.binding.executePendingBindings()
    }

    override fun getItemCount(): Int {
        return differ.currentList.size
    }
    class ViewHolder(val binding : LayoutItemMessageBinding) : RecyclerView.ViewHolder(binding.root)
}